import { computed, defineComponent, onMounted, reactive, ref } from "vue";
import styles from "./PrePaidDepositAccount.module.less";
import PromptPopup from "./promptPopup/promptPopup";
import TransferAccountsPopup from "./transferAccountsPopup/transferAccountsPopup";
import OnlineRechargePopup from "./OnlineRechargePopup/OnlineRechargePopup";
import { useStore as useUserStore } from "@/store/user";
import CertificatePopup from "./certificatePopup/certificatePopup";
import { $getAccountList, $getAccountStatistic, $getRechargeList } from "@/api/userCenter/PrePaidDepositAccount/PrePaidDepositAccount";
import useXlsx from "@/hooks/useXlsx";
import { message, Modal, Progress, Spin } from "ant-design-vue";
export default defineComponent({
  name:'userCenterPrePaidDepositAccount',
  setup() {
    const userStore = useUserStore();
    const xlsx = useXlsx();

    const state = reactive({
      balance: 0.00,
      accumulatedRecharge: 0.00,
      balancePayment: 0.00,
      refund: 0.00,
    })


    //期间累计充值金额
    const accumulatedRecharge = computed(() => {
      const sum = depositList.list?.filter((item: any) => item.from_type === 'member_recharge' || item.from_type === 'offline_recharge').reduce((sum: any, itemY: any) => (
        sum + parseFloat(itemY.account_data)
      ), 0)
      return parseFloat(sum.toFixed(2))
    })

    //余额支付金额
    const balancePayment = computed(() => {
      const sum = depositList.list?.filter((item: any) => item.from_type === 'pay_order').reduce((sum: any, itemY: any) => (
        sum + parseFloat(itemY.account_data)
      ), 0);
      return parseFloat(sum.toFixed(2))
    })

    //账户余额
    const PaymentAccountBalance = () => (
      <div class={styles.paymentAccountBalance}>
        <div class={styles['payment-account-module']}>
          <div class={styles['now-balance']}>当前账户余额（元）</div>
          <div class={styles['balance-mone']}>{state.balance || 0.00}</div>
          {/* <div class={styles['remind']}>
            提醒：余额低于 1000.00 元 <span onClick={() => { PromptPopupRef.value.open(); }}>设置</span>
          </div> */}
          <div class={styles['button-box']}>
            <div class={styles.btn1} onClick={() => { message.info('暂时未开通此功能') }}>在线充值</div>
            <div class={styles.btn2} onClick={() => { transferAccountsPopupRef.value.open() }}>转账充值</div>
          </div>
        </div>
        <div class={styles['top-up-statistics']}>
          <div class={styles['statistics-item']}>
            <span class={styles['item-label']}>期间累计充值(元):</span>
            <span class={styles['item-value']}>{state.accumulatedRecharge || 0.00}￥</span>
          </div>
          <div class={styles['statistics-item']}>
            <span class={styles['item-label']}>余额支付(元):</span>
            <span class={styles['item-value']}>{state.balancePayment || 0.00}￥</span>
          </div>
          {/* <div class={styles['statistics-item']}>
            <span class={styles['item-label']}>退款(元):</span>
            <span class={styles['item-value']}>{state.refund || 0}￥</span>
          </div> */}
        </div>
      </div>
    )

    const searchForm = reactive({
      time: [], //交易时间
      startDate: null,   //交易时间
      endDate: null,
      serialNumber: '',  //流水号
      branch: '',        //分社名称
      consumptionType: null,//审核状态
      order_status: null,//充值状态
    })

    //审核状态
    const consumptionTypes = ref([
      {
        label: '待审核',
        value: 0,
      },
      {
        label: '拒绝',
        value: -1,
      },
      {
        label: '通过',
        value: 1,
      },
    ])

    //充值状态
    const ordestatus = ref([
      {
        label: '成功',
        value: 1,
      },
      {
        label: '失败',
        value: -1,
      },
    ])

    const depositList = reactive({
      list: [],
      columns: [
        {
          title: "提交时间",
          dataIndex: "create_time",
          align: "center",
          width: "180px",
        },
        {
          title: "流水号",
          dataIndex: "order_no",
          align: "center",
          width: "150px",
        },
        {
          title: "金额（元）",
          dataIndex: "amount",
          align: "center",
          width: "140px",
        },
        {
          title: "类型",
          dataIndex: ["type", "label"],
          align: "center",
          width: "150px",
        },
        {
          title: "充值状态",
          dataIndex: ["order_status", "label"],
          align: "center",
          width: "120px",
        },
        {
          title: "审核状态(转账充值)",
          dataIndex: ["verify_status", "label"],
          align: "center",
          width: "160px",
        },
        {
          title: "审核时间(转账充值)",
          dataIndex: "verify_time",
          align: "center",
          width: "180px",
        },
        {
          fixed: "right",
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "100px",
        }
      ],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
      loading: false,
    })

    //查询
    const clickSearch = () => {
      getList();
    }
    //重置
    const reset = () => {
      searchForm.time = [];
      searchForm.serialNumber = '';
      searchForm.consumptionType = null;
      searchForm.order_status = null;
    }

    //获取缴存记录
    const getList = () => {
      depositList.loading = true;
      $getRechargeList({
        page: depositList.pagination.current,
        limit: depositList.pagination.pageSize,
        order_no: searchForm.serialNumber || undefined,
        create_begin: searchForm.time.length > 1 ? String((new Date(searchForm.time[0]).getTime() / 1000).toFixed(0)) : undefined,
        create_end: searchForm.time.length > 1 ? String((new Date(searchForm.time[1]).getTime() / 1000).toFixed(0)) : undefined,
        verify_status: searchForm.consumptionType || undefined,
        order_status: searchForm.order_status || undefined,
      }).then((res: any) => {
        depositList.loading = false;
        depositList.list = res.data?.data || [];
        depositList.pagination.total = res?.data?.total || '';
        depositList.pagination.current = res.data?.current_page || '';
        depositList.pagination.pageSize = res?.data?.per_page || '';
      }).catch(() => {
        depositList.loading = false;
      })
    }
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      depositList.pagination.current = pag.current;
      depositList.pagination.pageSize = pag.pageSize;
      getList();
      // const dom: any = document.getElementById("app");
      // dom.scrollTop = 250;
    };

    onMounted(() => {
      getList();
      $getAccountStatistic().then((res: any) => {
        state.balance = res.data?.balance || '';
        state.accumulatedRecharge = res.data?.rechargeSum || '';
        state.balancePayment = res.data?.paySum || '';
      })
    })
    //时间change
    const timeChange = () => {
      if (searchForm.time === null) {
        searchForm.time = [];
      }
    }
    //缴存记录
    const PrePaidDepositContent = () => (
      <div class={styles['prePaid-deposit-content']}>
        <div class={styles['search-form']}>
          <div class={styles['search-form-row']}>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>交易时间</div>
              <a-range-picker v-model:value={[searchForm.time]} valueFormat="YYYY-MM-DD" style="margin-left: 10px;" onChange={()=>{timeChange()}}></a-range-picker>
            </div>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>流水号</div>
              <a-input style="width:78%;" v-model:value={searchForm.serialNumber}></a-input>
            </div>
          </div>
          <div class={styles['search-form-row']}>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>充值状态</div>
              <a-select
                v-model={[searchForm.order_status, "value"]}
                options={ordestatus.value}
                style="width:35%;height:32px;margin-right:30px"
                allowClear={true}
                placeholder="请选择"
              >
              </a-select>
            </div>
            <div class={styles['search-form-item']}>
              <div class={styles['item-label']}>审核状态</div>
              <a-select
                v-model={[searchForm.consumptionType, "value"]}
                options={consumptionTypes.value}
                style="width:30%;height:32px;margin-right:30px"
                allowClear={true}
                placeholder="请选择"
              >
              </a-select>
              <div class={[styles['item-btn'], styles.plain]} onClick={() => { reset() }}>重置</div>
              <div class={styles['item-btn']} onClick={() => { clickSearch() }}>查询</div>
              <div class={styles['item-btn']} onClick={async () => {
                xlsx.init({
                  limit: 2000,
                  otherParams: {},
                  service: $getAccountList,
                })
                await xlsx.defineList([
                  {
                    label: "编号",
                    value: "id",
                    width: 25,
                  },
                  {
                    label: "交易时间",
                    value: "create_time",
                    width: 25,
                  },
                  {
                    label: "交易内容",
                    value: "remark",
                    width: 25,
                  },
                  {
                    label: "金额（元）",
                    value: "account_data",
                    width: 25,
                  },
                  {
                    label: "交易方式",
                    value: "type_name",
                    width: 25,
                  },
                ]);
                await xlsx.exportToExcel('缴存记录.xlsx');
              }}>导出记录</div>
            </div>
          </div>
        </div>
        <div class={styles['deposit-form']}>
          <div class={styles['statistical']}>共有{depositList.pagination.total || 0}条充值记录</div>
          <a-table
            columns={depositList.columns}
            bordered={true}
            scroll={{ x: "max-content" }}
            dataSource={depositList.list}
            onChange={tableChangeHandler}
            rowKey="id"
            pagination={depositList.pagination}
            loading={depositList.loading}
            v-slots={{
              bodyCell: ({ column, record }: any) => {
                // 操作栏
                if (column.dataIndex === "operation") {
                  return (
                    <div class={styles['operate']}>
                      {
                        record.type.value === 1 && <a-button
                          type="primary"
                          size="small"
                          onClick={() => {
                            certificatePopupRef.value.open(record)
                          }}
                        >查看凭证</a-button>
                      }
                    </div>
                  );
                }
              },
            }}
          />
        </div>
      </div>
    )
    const PromptPopupRef = ref(null as any);
    const transferAccountsPopupRef = ref(null as any);
    const onlineRechargePopupRef = ref(null as any);
    const certificatePopupRef = ref(null as any);
    return () => (
      <div class={styles.PrePaidDepositAccount}>
        <div class={styles['header-box']}>充值记录</div>
        <PaymentAccountBalance />
        <PrePaidDepositContent />
        <PromptPopup ref={PromptPopupRef} />
        <TransferAccountsPopup ref={transferAccountsPopupRef} />
        <OnlineRechargePopup ref={onlineRechargePopupRef} />
        <CertificatePopup ref={certificatePopupRef} />
        <Modal
          title={'正在导出记录'}
          visible={['doing'].includes(xlsx.state.running)}
          closable={false}
          footer={null}
        >
          <div class={styles["progress_box"]}>
            {
              xlsx.state.running === "doing" && xlsx.progress.value < 100 && (
                <Progress type="circle" percent={xlsx.progress.value} />
              )
            }
            {
              xlsx.state.running === "doing" && xlsx.progress.value === 100 && (
                <Spin tip="正在导出文件,请勿关闭当前页面..." size="large" />
              )
            }
          </div>
        </Modal>
      </div>
    )
  }
})